CREATE PROCEDURE [dbo].[AppointmentSave]
@UBRN				INT, 
@PatientId			UNIQUEIDENTIFIER,
@ReferrerId			UNIQUEIDENTIFIER,
@ProviderId			UNIQUEIDENTIFIER,
@ClinicTypeId		UNIQUEIDENTIFIER,
@SlotId				UNIQUEIDENTIFIER,
@CreatedDate		DATETIME,
@StartDateTime		DATETIME,
@EndDateTime		DATETIME,
@UpdatedDate		DATETIME,
@CancelledBy		UNIQUEIDENTIFIER,
@CancelledDate		DATETIME,
@CancellationReason	NVARCHAR(100),
@Status				INT,
@Comments			NVARCHAR(MAX),
@ReminderDate		DATETIME,
@WorkflowId			UNIQUEIDENTIFIER

AS

DECLARE	@RowCount AS INT
DECLARE @Error AS INT

UPDATE	Appointment
SET		PatientId			= ISNULL(@PatientId,PatientId),
		ReferrerId			= ISNULL(@ReferrerId,ReferrerId),
		ProviderId			= ISNULL(@ProviderId,ProviderId),
		ClinicTypeId		= ISNULL(@ClinicTypeId, ClinicTypeId),
		SlotId				= @SlotId,
		CreatedDate			= ISNULL(@CreatedDate, CreatedDate),
		StartDateTime		= ISNULL(@StartDateTime, StartDateTime),
		EndDateTime			= ISNULL(@EndDateTime, EndDateTime),
		CancelledBy			= ISNULL(@CancelledBy, CancelledBy),
		CancelledDate		= ISNULL(@CancelledDate, CancelledDate),
		CancellationReason	= ISNULL(@CancellationReason, CancellationReason),
		Status				= ISNULL(@Status, Status),
		UpdatedDate			= ISNULL(@UpdatedDate, UpdatedDate),
		Comments			= ISNULL(@Comments, Comments),
		ReminderDate		= ISNULL(@ReminderDate, ReminderDate),
		WorkflowId			= ISNULL(@WorkflowId, WorkflowId)
WHERE	UBRN = @UBRN

SELECT @Error = @@ERROR, @RowCount = @@ROWCOUNT

IF @Error  <> 0
BEGIN
	RAISERROR('ERROR::AppointmentSave:Error in',16,1)
END

IF @RowCount  > 0
BEGIN
	RETURN @RowCount 
END

--	If adding for first time enter all the details including UBRN
INSERT	INTO Appointment (UBRN, PatientId, ReferrerId, ProviderId, ClinicTypeId, SlotId, CreatedDate, StartDateTime, EndDateTime, CancelledBy, CancelledDate, CancellationReason, Status, UpdatedDate, Comments, ReminderDate, WorkflowId)		
VALUES	(@UBRN, @PatientId, @ReferrerId, @ProviderId, @ClinicTypeId, @SlotId, @CreatedDate, @StartDateTime, @EndDateTime, @CancelledBy, @CancelledDate, @CancellationReason, @Status, @UpdatedDate, @Comments, @ReminderDate, @WorkflowId)		

SELECT	@Error = @@ERROR, @RowCount = @@ROWCOUNT

IF @Error  <> 0
BEGIN
	RAISERROR('ERROR::AppointmentNew:Error in',16,1)
END

RETURN @RowCount